<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Request;
class Tqr
{
    public $return_data=['Code'=>1,'Msg'=>'','ErrorSql'=>'','Data'=>[]];
    public function qr($input)
    {
        $gid = isset($input['gid'])?intval($input['gid']):0;
        $where[] =['id','=',$gid];
        $goods =Db::name('goods')->where($where)->find();
        if (!$goods){
            $this->return_data['Msg'] = "无此商品";
            return $this->print_result($this->return_data);
        }
        $appid = config('appid');
        $appsecret = config('appsecret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
        $at =file_get_contents($url);
        $at = json_decode($at,true);
        $qrurl = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$at['access_token'];
        $qrdata['path'] = '/pages/detail/detail?gid='.$gid;
        $qrinfo = curl_data($qrurl,json_encode($qrdata));
        $filename='goods_cover_'.uniqid()."_".mt_rand(10000,99999).'.png';
        $datepath = date('Ymd');
        $filepath = '/upload/cover/'.date('Ymd').'/'.$filename;
        $basepath = config('cover_folder').date('Ymd');
        if(!is_dir($basepath)){
          mkdir($basepath);
        }
        $file=$basepath.'/'.$filename;
        if (!file_put_contents($file,$qrinfo)){
            $this->return_data['Msg']="上传错误";
            return $this->print_result($this->return_data);
        }
        $c['cover'] = get_base_img($filepath);
        $c['path'] = $filepath;
        $this->return_data['Code']=0;
        $this->return_data['Msg']='成功';
        $this->return_data['Data']=$c;// 商品封面
        return $this->print_result($this->return_data);
    }
    public function print_result($return_data){
        if(!is_array($return_data)){
            $return_data['Code']=0;
            $return_data['Msg']='输出信息不符合规范';
        }
        return json($return_data)->code(200)->header(['Content-Type' => 'application/json']);
    }
}
